<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="入库批次号" prop="storeNumber">
        <el-input
          v-model="queryParams.storeNumber"
          placeholder="请输入入库批次号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
          
        />
      </el-form-item>
      <el-form-item label="入库日期" prop="storeDate">
        <el-date-picker
          clearable
          size="small"
          v-model="queryParams.storeDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择入库日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="仓库" prop="storeId">
        <storehouse-input
          ref="storehouseParams"
          :storehouse-props.sync="storehouseData"
          v-model="queryParams.storeName"
        />
      </el-form-item>
      <el-form-item label="门店类型" prop="sId">
          <el-select v-model="queryParams.sId"  placeholder="请选择门店类型">
            <el-option
              v-for="dict in storeListOptions"
              :key="dict.id"
              :label="dict.name"
              :value="parseInt(dict.id)"
            ></el-option>
          </el-select>
        </el-form-item>
      <el-form-item label="入库单状态" prop="storeStatus">
        <el-select
          v-model="queryParams.storeStatus"
          placeholder="请选择入库单状态"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in storeStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="入库类型" prop="storeType">
        <el-select
          v-model="queryParams.storeType"
          placeholder="请选择入库类型"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in storeTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['supplier:storeIn:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['supplier:storeIn:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['supplier:storeIn:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['supplier:storeIn:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="storeInList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55px" align="center" />
      <el-table-column label="ID" align="center" prop="id" width="55px" />
      <el-table-column label="入库批次号" align="center" prop="storeNumber" width="160px"/>
      <el-table-column
        label="入库日期"
        align="center"
        prop="storeDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.storeDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="仓库" align="center" prop="storeName" />
      <el-table-column label="门店类型" align="center" prop="sName" />
      <el-table-column label="入库类型" align="center" prop="storeType" :formatter="storeTypeFormat" width="80px"/>
      <el-table-column label="入库单状态"  align="center"  prop="storeStatus"   :formatter="storeStatusFormat" width="90px"  />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['supplier:storeIn:edit']"
            v-show="scope.row.storeStatus === 0"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-show="scope.row.storeStatus === 0"
            v-hasPermi="['supplier:storeIn:remove']"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['supplier:storeIn:view']"
            >查看</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改入库对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      :fullscreen="true"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="入库批次号" prop="storeNumber">
          <el-input
            v-model="form.storeNumber"
            placeholder="请输入入库批次号"
            prefix-icon="el-icon-edit"
            maxlength="48"
            show-word-limit
            :disabled="true"
          />
        </el-form-item>
        <el-form-item label="入库日期" prop="storeDate">
          <el-date-picker
            clearable
            size="small"
            v-model="form.storeDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择入库日期"
            :disabled="showView"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="仓库名称" prop="storeName">
          <storehouse-input 
            ref="storehouseParams"
            :storehouse-props.sync="storehouseData"
            v-model="form.storeName"
          />
        </el-form-item>
        <el-form-item label="门店类型" prop="sId">
          <el-select v-model="form.sId" :disabled="showView" placeholder="请选择门店类型">
            <el-option
              v-for="dict in storeListOptions"
              :key="dict.id"
              :label="dict.name"
              :value="parseInt(dict.id)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入库单状态" prop="storeStatus">
          <el-select v-model="form.storeStatus" :disabled="showView" placeholder="请选择入库单状态">
            <el-option
              v-for="dict in storeStatusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            rows="5"
            placeholder="请输入内容"
            maxlength="250"
            show-word-limit
            :disabled="showView"
          />
        </el-form-item>
        <el-divider content-position="center">入库明细信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAddPriceStore"
              v-show="!showView"
              >验货入库</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAddTbStoreInDetail"
              v-show="!showView"
              >添加</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="handleDeleteTbStoreInDetail"
              v-show="!showView"
              >删除</el-button
            >
          </el-col>
        </el-row>
        <el-table
          :data="tbStoreInDetailList"
          :row-class-name="rowTbStoreInDetailIndex"
          @selection-change="handleTbStoreInDetailSelectionChange"
          ref="tbStoreInDetail"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="序号"
            align="center"
            prop="index"
            width="50"
          />
          <el-table-column
            label="商品分类"
            align="center"
            prop="typeName"
            width="80px"
          />
          <el-table-column label="商品编号" align="center" prop="productSn" />
          <el-table-column label="品牌名称" align="center" prop="brandDesc" />
          <el-table-column label="商品名称" prop="productName" />
          <el-table-column label="规格" prop="itemName" />
           <el-table-column label="计量单位" prop="measurement" min-width="50px" :formatter="measurementFormat" />
          <el-table-column label="当前库存数量" prop="storeCount" min-width="80px" />
          <el-table-column label="是否包装类型" prop="isPack" :formatter="isPackFormat"/>
          <el-table-column label="数量" prop="qty" min-width="80px">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.qty"
                controls-position="right"
                placeholder="请输入数量"
                size="mini"
                :step="1"
                step-strictly
                :min="1"
                :disabled="showView"
                
              />
            </template>
          </el-table-column>
          <el-table-column
            label="生产日期"
            prop="productDate"
            min-width="115px"
          >
            <template slot-scope="scope">
              <el-date-picker
                clearable
                size="small"
                v-model="scope.row.productDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择生产日期"
                :disabled="showView"
              >
              </el-date-picker>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm(0)" v-show="!showView">保 存</el-button>
        <el-button type="success" @click="submitForm(1)" v-show="!showView">提 交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--选中商品组件-->
    <product-dialog
      :product-props.sync="productData"
      :handle-select="handleSelect"
      ref="productParams"
    />

    <check-productdetail-dialog
      :product-props.sync="productData"
      :handle-select="handleCheck"
      :radiobox="false"
      ref="checkProductdetail"
    />
  </div>
</template> 
<script>
import {
  listStoreIn,
  getStoreIn,
  delStoreIn,
  addStoreIn,
  updateStoreIn,
  exportStoreIn,
  generateNumber,
} from "@/api/supplier/storeIn";
import storehouseInput from "@/views/supplier/storehouse/input";
import productDialog from "@/views/supplier/product/dialog";
import checkProductdetailDialog from "@/views/supplier/checkProductdetail/dialog";
import { listStore } from "@/api/supplier/store";
export default {
  name: "StoreIn",
  components: {
    storehouseInput,
    productDialog,
    checkProductdetailDialog,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedTbStoreInDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 入库表格数据
      storeInList: [],
      // 入库明细表格数据
      tbStoreInDetailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查看标识
      showView: false,
      // 入库单状态字典
      storeStatusOptions: [],
       // 入库类型字典
      storeTypeOptions: [],
      // 包装类型
      typeOptions:[],
      // 计量单位字典
      measurementOptions: [],
      //门店类型
      storeListOptions:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        storeNumber: null,
        storeDate: null,
        storeId: null,
        storeStatus: null,
        orderByColumn: "id",
        isAsc: "desc"
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
         storeDate: [
          { required: true, message: "入库日期不能为空", trigger: "change" }
        ],
        sId: [
          { required: true, message: "门店类型不能为空", trigger: "change" }
        ], 
        storeName:[
          { required: true, message: "仓库名称不能为空", trigger: "change" }
        ],

        
      },
      storehouseData: {
        id: null,
        storeName: null,
      },
      productData: {
        open: false,
        currentQtyShow: true,
        productList: [],
      },
    };
  },
  created() {
    this.getList();
    this.getDicts("bus_storein_type").then((response) => {
      this.storeStatusOptions = response.data;
    });
    this.getDicts("bus_storeinout_type").then((response) => {
      this.storeTypeOptions = response.data;
    });
    this.getDicts("bus_measurement").then(response => {
      this.measurementOptions = response.data;
    });
    this.getDicts("sys_yes_no").then(response => {
      this.typeOptions = response.data;
    });
    this.getListStore();
  },
  methods: {
    /** 查询入库列表 */
    getList() {
      this.loading = true;
      listStoreIn(this.queryParams).then((response) => {
        this.storeInList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getListStore(){
      listStore(null).then((response) =>{
        this.storeListOptions = response.rows;
      });
    },

    // 入库单状态字典翻译
    storeStatusFormat(row, column) {
      return this.selectDictLabel(this.storeStatusOptions, row.storeStatus);
    },
    storeTypeFormat(row, column){
      return this.selectDictLabel(this.storeTypeOptions, row.storeType);
    },
    isPackFormat(row,column){
      return this.selectDictLabel(this.typeOptions, row.isPack);
    },
        // 计量单位字典翻译
    measurementFormat(row, column) {
      return this.selectDictLabel(this.measurementOptions, row.measurement);
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        storeNumber: null,
        storeDate: null,
        storeId: null,
        storeType: 0,
        storeStatus: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.tbStoreInDetailList = [];
      
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.storeId = this.storehouseData.id;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.$refs.storehouseParams.scName = null;
      this.storehouseData.id = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      this.ids = selection.map((item) => {
        if(item.storeStatus>0){
           this.multiple=true;
        }
        return item.id
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.storeDate=new Date();
      this.$refs.productParams.queryParams.ids=[];
      this.$refs.storehouseParams.scName = null;
      this.storehouseData.id = null;
      this.open = true;
      this.showView=false;
      this.form.storeStatus = 0;
      this.title = "添加入库";
      generateNumber().then((response) => {
        this.form.storeNumber = response.msg;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      
      const id = row.id || this.ids;
      getStoreIn(id).then((response) => {
        this.form = response.data;
        if(this.form.storeStatus!=0){
          this.msgError("已提交数据，不能修改!");
          return;
        }
        generateNumber().then((response) => {
          this.form.storeNumber = response.msg;
        });

        if (
          response.data.tbStoreInDetailList != null &&
          response.data.tbStoreInDetailList[0].id != null
        ) {
          this.tbStoreInDetailList = response.data.tbStoreInDetailList;
        }
       
        this.storehouseData.storeName = this.form.storeName;
        this.storehouseData.id =this.form.storeId;
        this.$refs.storehouseParams.scName =  this.form.storeName;
        this.open = true;
        this.showView=false;
        this.title = "修改入库";
      });
    },
    /** 提交按钮 */
    submitForm(status) {
      let flag = true;
     
      this.tbStoreInDetailList.some((item) => {
        if (item.qty == null || item.qty == 0) {
         
          this.msgError(
            "【" +
              item.brandDesc +
              "的" +
              item.productName +
              item.itemName +
              "】的数量不为空"
          );

          flag = false;
          return true;
        }
      });


      if(flag){
          this.$refs["form"].validate((valid) => {
          if (valid) {
            this.form.tbStoreInDetailList = this.tbStoreInDetailList;
            this.form.storeId = this.storehouseData.id;
            this.form.storeStatus=status;
            if (this.form.id != null) {
              updateStoreIn(this.form).then((response) => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              this.form.storeType=0;
              addStoreIn(this.form).then((response) => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除入库编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(function () {
        
          return delStoreIn(ids);
        })
        .then((ret) => {
          if(ret.data!=null && ret.data==-1){
            this.msgError("包含已提交数据，不能删除!");
          }
          else {
            this.getList();
            this.msgSuccess("删除成功");
          }
        });
    },
    /** 入库明细序号 */
    rowTbStoreInDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 选择验货入库单 */
    handleAddPriceStore(){
      if(this.storehouseData.id==null || this.form.sId==null){
        this.msgError("请选择仓库和门店类型");
        return;
      }


      if (this.tbStoreInDetailList.length > 0) {
        this.tbStoreInDetailList.map((item) => {
          var index = this.$refs.checkProductdetail.queryParams.ids.findIndex(
            function (value) {
              return (value = item.checkId);
            }
          );
          if (index == -1) {
            this.$refs.checkProductdetail.queryParams.ids.push(item.checkId);
          }
        });
      }

  

      this.$refs.checkProductdetail.queryParams.checkType=0; // 验货入库
      this.$refs.checkProductdetail.queryParams.checkStatus=1; // 已验货
      this.$refs.checkProductdetail.queryParams.storeId=this.storehouseData.id; // 仓库ID
      this.$refs.checkProductdetail.queryParams.sId=this.form.sId; // 门店类型ID

      this.$refs.checkProductdetail.open = true;
      this.$refs.checkProductdetail.getList();

    },
    /** 入库明细添加按钮操作 */
    handleAddTbStoreInDetail() {

      if(this.storehouseData.id==null || this.form.sId==null){
        this.msgError("请选择仓库和门店类型");
        return;
      }

      if (this.tbStoreInDetailList.length > 0) {
        this.tbStoreInDetailList.map((item) => {
          var index = this.$refs.productParams.queryParams.ids.findIndex(
            function (value) {
              return (value = item.priceId);
            }
          );
          if (index == -1) {
            this.$refs.productParams.queryParams.ids.push(item.priceId);
          }
        });
      }
      this.$refs.productParams.queryParams.storeId=this.storehouseData.id;
      this.$refs.productParams.queryParams.sId=this.form.sId;
 
      this.$refs.productParams.open = true;
      this.$refs.productParams.getProductList();
    },
    /** 入库明细删除按钮操作 */
    handleDeleteTbStoreInDetail() {
      if (this.checkedTbStoreInDetail.length == 0) {
        this.$alert("请先选择要删除的入库明细数据", "提示", {
          confirmButtonText: "确定",
        });
      } else {
        this.checkedTbStoreInDetail.forEach((item) => {
          for (let i = 0; i < this.tbStoreInDetailList.length; i++) {
            if (this.tbStoreInDetailList[i].id == item.id) {
              this.tbStoreInDetailList.splice(i, 1);
              this.$refs.productParams.queryParams.ids.splice(i, 1);
              this.$refs.productParams.productList.push(item);
              this.$refs.checkProductdetail.queryParams.ids.splice(i, 1);
              break;
            }
          }
        });

        this.checkedTbStoreInDetail = [];
      }
    },
    /** 单选框选中数据 */
    handleTbStoreInDetailSelectionChange(selection) {
      this.checkedTbStoreInDetail = selection;
    },
    handleSelect(data) {
      data.forEach((item) => {
        this.tbStoreInDetailList.push(item);
      });
    },
    handleCheck(data){
       data.forEach((item) => {
        this.tbStoreInDetailList.push(item);
      });
    },


    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有入库数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportStoreIn(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      const id = row.id || this.ids;
      getStoreIn(id).then((response) => {
        this.form = response.data;
        if (
          response.data.tbStoreInDetailList != null &&
          response.data.tbStoreInDetailList[0].id != null
        ) {
          this.tbStoreInDetailList = response.data.tbStoreInDetailList;
        }
        this.showView = true;
        this.storehouseData.storeName = this.form.storeName;
        this.$refs.storehouseParams.scName =  this.form.storeName;
        this.open = true;
        this.title = "查看入库";
      });
    },
  },
};
</script>
